#pragma once

#include <iostream>
#include <sys/ipc.h>    // Inter-Process Communication
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <cstring>

const std::string pathname = "/home/LHY/test/shm";  // 项目路径
const int proj_id = 0x11223344;                     // 项目id

const std::string filename = ".fifo";

// 共享内存的大小，强烈建议设置成4096的整数倍
const int size = 4096;


key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    // 判断是否ftok成功
    if (key < 0)
    {
        std::cerr << "errno: " << errno << ", errstring" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

// 转16进制
std::string ToHex(int key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}


int CreateShmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(2);    // 创建失败直接退出
    }

    return shmid;
}

int CreateShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT|IPC_EXCL|0644);
}

int Getshm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT/*0也可以*/);
}

bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }

    std::cout << "mkfifo success... read" << std::endl;
    return true;
}
